package com.dz.util;

import jakarta.mail.*;
import jakarta.mail.internet.InternetAddress;
import jakarta.mail.internet.MimeMessage;

import java.util.Properties;

public class EmailUtil {

    private static final String FROM = "3215261712@qq.com";
    private static final String AUTH_CODE = "myrnceajybnzdcfc";
    private static final String HOST = "smtp.qq.com";
    private static final String PORT = "465";

    private static final Session session;
    static {
        Properties props = new Properties();
        props.put("mail.smtp.host", HOST);
        props.put("mail.smtp.port", PORT);
        props.put("mail.smtp.auth", "true");
        props.put("mail.smtp.ssl.enable", "true");
        session = Session.getInstance(props, new Authenticator(){
            @Override
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(FROM, AUTH_CODE);
            }
        });
        //开启debug模式，可以查看发送邮件的运行状态
        session.setDebug(true);
    }


    public static void sendEmail(String target, String text) throws MessagingException {
        Message message = new MimeMessage(session);
        try {
            message.addFrom(new Address[]{new InternetAddress(FROM)});
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(target));
            message.setSubject("【“颜途”】地陪服务平台");
            message.setContent("<h1 style='color:red'>验证码:"+text+"，有效时间3分钟</h1>", "text/html;charset=utf-8");
            Transport.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
            throw e;
        }
    }

    public static void sendWorkEmail(String target, String text) throws MessagingException {
        Message message = new MimeMessage(session);
        try {
            message.addFrom(new Address[]{new InternetAddress(FROM)});
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(target));
            message.setSubject("【“颜途”】地陪服务平台");
            message.setContent("<h1 style='color:red'>"+text+"</h1>", "text/html;charset=utf-8");
            Transport.send(message);
        } catch (MessagingException e) {
            e.printStackTrace();
            throw e;
        }
    }
}
